package org.com.money.componet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.com.money.service.MoneyException;

public class PropertiesComponetImpl implements PropertiesComponet {
	

	public static void main(String[] args) {
		PropertiesComponet propertiesComponet = new PropertiesComponetImpl();
		//
		Map<String, String> users = new HashMap<String, String>();

		users.put("W-001", "xxx");
		users.put("W-002", "測試");
		propertiesComponet.writeXml(users, "xxxx.xml");

		// System.out.print(MessageUtils.getContentByCode("W-001"));

	}

	
	@Override
	public void writeXml(Map<String, String> map, String outputfilePath)
			throws MoneyException {
		System.out.println("writeXml init");

		final Properties properties = new Properties();

		try {

			final File f = new File(outputfilePath);
			if (f.exists()) {
				f.delete();
				f.createNewFile();
			} else {
				f.createNewFile();
			}

			for (String key : map.keySet()) {
				properties.put(key, map.get(key));
			}

			System.out.println(properties);
			properties.storeToXML(new FileOutputStream(outputfilePath),
					"wirteProperties");

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			properties.clear();
		}
		System.out.println("writeXml end");

	}

	@Override
	public Map<String, Object> outputfilePath(File f) throws MoneyException {
		final Properties properties = new Properties();

		final Map<String, Object> map = new HashMap<String, Object>();
		try {

			properties.load(new FileInputStream(f));

			for (Object key : properties.keySet()) {
				map.put((String) key, properties.get(key));
			}
			return map;

		} catch (Exception e) {
			e.printStackTrace();
			throw new MoneyException(null, "");
		} finally {
			properties.clear();
		}

	}

	@Override
	public void wirteProperties(Map<String, String> map, String outputfilePath)
			throws MoneyException {

		final Properties properties = new Properties();

		try {

			final File f = new File(outputfilePath);
			if (f.exists()) {
				f.delete();
				f.createNewFile();
			} else {
				f.createNewFile();
			}

			for (String key : map.keySet()) {
				properties.put(key, map.get(key));
			}
			properties.store(new FileOutputStream(outputfilePath), "store");

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			properties.clear();
		}

	}

	@Override
	public Map<String, Object> outputfilePath(String f) throws MoneyException {

		return this.outputfilePath(new File(f));
	}
}
